import csv
from app import app, db, Course, CourseComment  # 从 app.py 中导入 app 和 db 对象

def import_courses():
    if Course.query.count() == 0:
        with open('course_data.csv', newline='', encoding='gbk') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                course = Course(
                    courseId=row['courseId'],
                    name=row['name'],
                    enrollCount=int(row['enrollCount']),
                    teacherName=row['teacherName'],
                    schoolName=row['schoolName']
                )
                db.session.add(course)
            db.session.commit()
        print("Courses imported successfully.")

def import_comments():
    if CourseComment.query.count() == 0:
        with open('course_comment_data.csv', newline='', encoding='gb18030') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                comment = CourseComment(
                    id=int(row['id']),
                    courseId=row['courseId'],
                    commentorId=row['commentorId'],
                    userNickName=row['userNickName'],
                    content=row['content'],
                    mark=int(row['mark']) if row['mark'].isdigit() else None,
                    status=row['status']
                )
                db.session.add(comment)
            db.session.commit()
        print("Comments imported successfully.")

from app import app, db, Course, CourseComment  # 确保导入正确

def query_courses():
    courses = Course.query.all()
    print("Courses:")
    for course in courses:
        print(course.courseId, course.name, course.enrollCount, course.teacherName, course.schoolName)

def query_comments():
    comments = CourseComment.query.all()
    print("Comments:")
    for comment in comments:
        print(comment.id, comment.courseId, comment.userNickName, comment.content)


if __name__ == "__main__":
    with app.app_context():  # 确保在应用上下文中运行
        db.create_all()  # 创建数据库表
        import_courses()  # 导入课程数据
        import_comments()  # 导入评论数据
        query_courses()
        query_comments()